//
//  CLTool.m
//  CL1024
//
//  Created by liu nian on 13-1-30.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "CLTool.h"
#import "ASIHTTPRequest.h"
#import "MBProgressHUD.h"
#import "ASIFormDataRequest.h"
#import "CLReachability.h"
#import "YBModalAlert.h"



@implementation CLTool

// 导航栏按钮
+ (UIButton *)getNavButton:(SEL)backAction ButtonTarget:(id)target backImage:(NSString *)backImageName iconImage:(NSString *)iconImageName {
    // 按钮背景图
    UIImage *navButtonImage = [UIImage imageNamed:backImageName];
    navButtonImage = [navButtonImage stretchableImageWithLeftCapWidth:5 topCapHeight:5];
    
    // 导航栏按钮
    UIButton *barButton = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 30)] autorelease];
    barButton.imageView.contentMode = UIViewContentModeCenter;
    [barButton setBackgroundImage:navButtonImage forState:UIControlStateNormal];
    [barButton addTarget:target action:backAction forControlEvents:UIControlEventTouchUpInside];
    
    // 按钮上图标
    UIImage *iconImage = [UIImage imageNamed:iconImageName];
    UIImageView *iconImageView = [[[UIImageView alloc] initWithImage:iconImage] autorelease];
    [barButton insertSubview:iconImageView atIndex:0];
    iconImageView.center = barButton.center;
    
    return barButton;
}

// 网络可用检查
+ (BOOL)reachabilityCheck {
	return [CLReachability networkAvailable];
}

+(NSString *)getCLResponseString:(NSString *)url andCurrentView:(UIView *)view
{
  //检测网络状态
    if (![CLTool reachabilityCheck]) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
        hud.mode =MBProgressHUDModeText;
        hud.labelText = @"哎呦! 网络不通没办法看了..";
        [hud hide:YES afterDelay:5];
        return nil;
    }
    //启动任务等待指示器
//    MBProgressHUD *progesshud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    NSURL *targetUrl = [NSURL URLWithString:url];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:targetUrl];
    [request setTimeOutSeconds:30];
    [request addRequestHeader:@"Content-Type" value:@"application/xml;charset=gb2312;"];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        NSData *data = [request responseData];
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        NSString *str =[[[NSString alloc] initWithData:data encoding:enc] autorelease];
        // 以下一句很重要，将目标地址的页面编码变成utf-8,否则页面解析不成功
        str =  [str stringByReplacingOccurrencesOfString:@"gb2312" withString:@"utf-8"];
        return str;
    }else{
//        [progesshud hide:YES];
        NSLog(@"%@",error);
        //如果因为发生error错误，则返回error，调用者根据error做相应处理
        return [NSString stringWithFormat:@"error"];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
      
}

+ (BOOL)addPostToInstapaperWithTitle:(NSString *)title withUrl:(NSString *)url withUserName:(NSString *)username withPassword:(NSString *)password
{
    NSString *instapaperURL = @"https://www.instapaper.com/api/add";
    ASIFormDataRequest *formRequest = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:instapaperURL]] autorelease];
    // 请求方法
    [formRequest setRequestMethod:@"POST"];
    // 超时请求次数
    [formRequest setNumberOfTimesToRetryOnTimeout:0];
    [formRequest setPostValue:title forKey:@"title"];
    [formRequest setPostValue:username forKey:@"username"];
    [formRequest setPostValue:password forKey:@"password"];
    [formRequest setPostValue:url forKey:@"url"];
    [formRequest startSynchronous];
    NSError *error = [formRequest error];
    if (!error) {
        int statusCode = [formRequest responseStatusCode];
        if (statusCode == 201) {
            return YES;
        }else{
            return NO;
        }
        
    }else{
        return NO;
    }
}

/*
+(NSString *)getCLResponseStringWithBlocks:(NSString *)url andCurrentView:(UIView *)view
{
    //启动任务等待指示器
    MBProgressHUD *progesshud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    NSURL *targetUrl = [NSURL URLWithString:url];
    __block NSString *responseString = nil;
     __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:targetUrl];
    //成功处理的block
    [request setCompletionBlock:^{
        [progesshud hide:YES];
        NSData *data = [request responseData];
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        responseString =[[[NSString alloc] initWithData:data encoding:enc] autorelease];
        responseString =  [responseString stringByReplacingOccurrencesOfString:@"gb2312" withString:@"utf-8"];
        NSLog(@"responseString:%@",responseString);
    }];
    //失败处理的block
    [request setFailedBlock:^{
        [progesshud hide:YES];
         NSError *error = [request error];
        NSLog(@"error:%@",error);
    }];
    //开始异步请求
    [request startSynchronous];
    
    
    return responseString;
}
*/

@end
